import {
  Injectable,
  NotFoundException,
  BadRequestException,
} from '@nestjs/common';
import { ResumeFile } from './resume.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class ResumeService {
  constructor(
    @InjectRepository(ResumeFile)
    private resumeRepository: Repository<ResumeFile>,
  ) {}

  findAll(): Promise<ResumeFile[]> {
    return this.resumeRepository.find();
  }

  async create(
    resume: Omit<ResumeFile, 'id' | 'createdAt'>,
  ): Promise<ResumeFile> {
    // 验证必填字段
    if (
      !resume.fileName ||
      !resume.username ||
      !resume.fileType ||
      !resume.filePath
    ) {
      throw new BadRequestException('All fields are required');
    }

    const newResume = this.resumeRepository.create({
      ...resume,
      createdAt: new Date(),
    });
    return await this.resumeRepository.save(newResume);
  }

  async update(id: number, resume: Partial<ResumeFile>): Promise<ResumeFile> {
    const existingResume = await this.resumeRepository.findOne({
      where: { id },
    });

    if (!existingResume) {
      throw new NotFoundException(`Resume with ID ${id} not found`);
    }

    await this.resumeRepository.update(id, resume);
    const updatedResume = await this.resumeRepository.findOne({
      where: { id },
    });

    if (!updatedResume) {
      throw new NotFoundException(
        `Resume with ID ${id} not found after update`,
      );
    }

    return updatedResume;
  }
}
